// 操作数据库User表
import { User } from '../entity/User'
import { manager } from '../data-source'
import { In } from 'typeorm'
import { removePrefix } from '../../utils/index'

/**
 * @description 新增用户（查看当前是否存在不存在插入存在则更新）
 */
export const getUser = async (username) => {
  return manager.findOneBy(User, { username })
}

// 查会员数据
export const getUserList = async (params, userId = '') => {
  // const list = await manager
  //   .createQueryBuilder(User, 'user')
  //   .where('(user.name LIKE :name or user.phone LIKE :phone) AND status =="1"', {
  //     name: `%${params.keyWords}%`,
  //     phone: `%${params.keyWords}%`
  //   })
  //   .orderBy('user.updatetime', 'DESC')
  //   .getRawMany()

  const total = await manager
    .createQueryBuilder(User, 'user')
    .select('COUNT(*)', 'count')
    .where('(user.name LIKE :name or user.phone LIKE :phone) AND status =="1"', {
      name: `%${params.keyWords}%`,
      phone: `%${params.keyWords}%`
    })
    .getRawMany()

  let user = []
  if (userId !== '') {
    user = await manager.getRepository('User').find({
      where: { id: userId },
      relations: ['frequency'] // 加载相关联的 posts
    })
  } else {
    user = await manager.getRepository('User').find({
      relations: ['frequency'] // 加载相关联的 frequency
    })
  }
  // const user = await manager.getRepository('User').find({
  //   // where: { id: In([1, 2]) },
  //   relations: ['frequency'] // 加载相关联的 frequency
  // })
  // console.log(user)

  let data = {
    list: user || [],
    total: total[0].count || 0
  }
  return await data
}

// 增加会员
export const addUser = async (data) => {
  const res = await manager.insert(User, [{ ...data, status: '1' }])
  return await true
}

// 更新会员
export const updateUser = async (id, data) => {
  const res = await manager.update(User, { id }, data)
  return await true
}

// 软删除会员
export const deleteUser = async (id) => {
  const res = await manager.update(User, { id }, { status: '0' })
  return await true
}

// 硬删除会员
export const gardDeleteUser = async (id) => {
  const res = await manager.delete(User, { id })
  return await true
}
